import axios, {
  AxiosInstance,
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";

const service: AxiosInstance = axios.create({
  baseURL: "http://129.204.225.193:8890/",
  timeout: 5000000,
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 默认参数
    var defaults = {};
    if (localStorage.getItem("userInfo")) {
      defaults = {
        operateAccountId: JSON.parse(localStorage.getItem("userInfo")).userId,
        operateAccountName: JSON.parse(localStorage.getItem("userInfo"))
          .userName,
      };
    } else {
      defaults = {
        operateAccountId: "admin",
        operateAccountName: "系统管理员",
      };
    }
    // 防止缓存，GET请求默认带_t参数
    if (config.method === "get") {
      config.params = {
        ...config.params,
      };
    }
    if (config.params) {
      config.params = {
        ...defaults,
        ...config.params,
      };
    }
    if (config.data) {
      config.data = {
        ...defaults,
        ...config.data,
      };
    }
    return config;
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response;
    } else {
      Promise.reject();
    }
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject();
  }
);

export default service;
